-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathkosaraju double pass algorithm.cpp
109 lines (97 loc) · 2.22 KB
/
kosaraju double pass algorithm.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
//template by chamow
#include<bits/stdc++.h>
/*-------------------------------------------------------- */
using namespace std;
/*-------------------------------------------------------- */
#define rep(i,val,n) for(ll i=val;i<n;i++)
#define per(j,val,n) for(ll j=val;j>=n;j--)
#define pb push_back
#define pi 3.14157
#define mp make_pair
#define MODULO 1000000007
#define INF 1000000000000000
#define fastread ios_base::sync_with_stdio(false); cin.tie(NULL);
/*-------------------------------------------------------- */
typedef long long ll;
typedef vector<bool> boolean;
typedef vector<ll> vec;
/*-------------------------------------------------------- */
ll gcd(ll a, ll b)
{
if(b == 0)
{
return a;
}
return gcd(b, a%b);
}
ll lcm(ll a, ll b)
{
return ((a*b)/gcd(a,b));
}
/*-------------------------------------------------------- */
stack<ll> S;
void dfs(vec *adj, boolean &visited, ll s)
{
visited[s] = true;
vec::iterator it;
for(it = adj[s].begin(); it != adj[s].end(); it++)
{
if(visited[*it] == false)
{
dfs(adj, visited, *it);
}
}
S.push(s);
}
void dfs_again(vec *revadj, boolean &visited_again, ll s)
{
visited_again[s] = true;
cout<<s<<" ";
vec::iterator it;
for(it = revadj[s].begin(); it != revadj[s].end(); it++)
{
if(visited_again[*it] == false)
{
dfs_again(revadj, visited_again, *it);
}
}
}
void kosaraju(vec *revadj, ll n)
{
boolean visited_again(n, false);
while(!S.empty())
{
ll start = S.top();
S.pop();
if(visited_again[start] == false)
{
dfs_again(revadj, visited_again, start);
cout<<endl;
}
}
}
int main()
{
fastread;
ll n, m, u, v;
cin>>n>>m;
vec *adj = new vec[n];
vec *revadj = new vec[n];
rep(i,0,m)
{
cin>>u>>v;
adj[u].pb(v);
revadj[v].pb(u);
}
boolean visited(n, false);
rep(i,0,n)
{
if(visited[i] == false)
{
dfs(adj, visited, i);
}
}
boolean visited_again(n, false);
kosaraju(revadj, n);
return 0;
}